package main

import (
	"flag"
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"os"
	"strings"
)

func handleError(err error) {
	fmt.Println("Error:", err)
	os.Exit(-1)
}

func main() {
	accessKeyId := "xxx"
	accessKeySecret := "xxxx"
	endpoint := flag.String("ep", "http://oss-cn-shanghai.aliyuncs.com", "aliyun OSS endpoint")
	bucketName := flag.String("bn", "", "aliyun OSS BucketName")
	objectName := flag.String("on", "", "aliyun oss objectName")
	downloadedFileName := flag.String("df", "", "downloadedFileName")
	ossPrefix := flag.String("op", "", "ossPrefix")
	action := flag.String("ac", "getFile", "download or getFile")

	client, err := oss.New(*endpoint, accessKeyId, accessKeySecret)
	flag.Parse()

	if err != nil {
		handleError(err)
	}
	bucket, err := client.Bucket(*bucketName)
	if err != nil {
		handleError(err)
	}
	if *action == "download" {
		err = bucket.GetObjectToFile(*objectName, *downloadedFileName)
		if err != nil {
			handleError(err)
		}
	}
	if *action == "getFile" {
		lsRes, err := bucket.ListObjects(oss.MaxKeys(10), oss.Prefix(*ossPrefix))
		if err != nil {
			fmt.Println("Error:", err)
			os.Exit(-1)
		}
		var test string
		for _, object := range lsRes.Objects {
			//fmt.Println("Object:", object.Key)
			arr := strings.Split(object.Key, "/")
			//fmt.Println("arr", arr[len(arr)-1])
			test = test + arr[len(arr)-1] + "\n"
		}
		fmt.Println(test)
	}
}
